package com.touzhijia.common.utils;

import com.touzhijia.common.vo.response.AjaxMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.util.List;

/**
 * 作者：lizw <br/>
 * 创建时间：2017/6/1 14:07 <br/>
 */
public class BeanValidatorUtils {
    /**
     * 日志对象
     */
    private final static Logger logger = LoggerFactory.getLogger(BeanValidatorUtils.class);

    /**
     * 将Spring验证信息放入AjaxMessage对象中<br/>
     * BindingResult中有错误AjaxMessage的Success属性就会被设置成False<br/>
     *
     * @param bindingResult Spring验证的错误消息
     * @param message       AjaxMessage对象
     * @return 验证有错误返回False，无错误返回True
     */
    public static boolean beanValidator(BindingResult bindingResult, AjaxMessage<?> message) {
        boolean hasErrors = bindingResult.hasErrors();
        if (hasErrors) {
            message.setSuccess(false);
            message.setSuccessMessage(null);
            message.setFailMessage("请求参数校验失败！");
            List<FieldError> validError = bindingResult.getFieldErrors();
            for (FieldError fieldError : validError) {
                String entityName = fieldError.getObjectName();
                String filed = fieldError.getField();
                String errorMessage = fieldError.getDefaultMessage();
                String code = fieldError.getCode();
                String value = fieldError.getRejectedValue() == null ? "null" : fieldError.getRejectedValue().toString();
                message.addValidMessage(fieldError);
                logger.debug("###数据验证失败 entityName:" + entityName
                        + " | filed:" + filed
                        + " | errorMessage:" + errorMessage
                        + " | code:" + code
                        + " | value:" + value);
            }
        }
        return !hasErrors;
    }
}
